package com.imooc.es_demo.controller;

import com.imooc.es_demo.entity.es.EsBlog;
import com.imooc.es_demo.entity.mysql.MysqlBlog;
import com.imooc.es_demo.repository.es.EsBlogRepository;
import com.imooc.es_demo.repository.mysql.MysqlBlogRepository;
import lombok.Data;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@Slf4j
public class DataController {
    @Autowired
    private EsBlogRepository esBlogRepository;

    @Autowired
    private MysqlBlogRepository mysqlBlogRepository;

    @GetMapping(value = "blogs")
    public Object blog(){
        List<MysqlBlog> mysqlBlogs = mysqlBlogRepository.queryAll();
        return mysqlBlogs;
    }

    @PostMapping("/search")
    public Object search(@RequestBody Param param){
        Map<String,Object> map  = new HashMap<>();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String type = param.getType();
        if("mysql".equalsIgnoreCase(type)){
            //mysql
            List<MysqlBlog> mysqlBlogs = mysqlBlogRepository.queryMysqlBlogsByTitleLikeOrContentLike(param.getKeyword());
            map.put("list",mysqlBlogs);
        }else if ("es".equalsIgnoreCase(type)){
            //es
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            String s = builder.should(QueryBuilders.matchPhraseQuery("title", param.getKeyword()))
                    .should(QueryBuilders.matchPhraseQuery("content", param.getKeyword()))
                    .toString();
            log.info("-------------S={}",s);
            Page<EsBlog> search = (Page<EsBlog> )esBlogRepository.search(builder);
            List<EsBlog> content = search.getContent();
            map.put("list",content);


        }else {
            return "I can't understand it";
        }
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        map.put("duration",totalTimeMillis);
        return map;

    }

    @GetMapping("/blog/{id}")
    public Object blog(@PathVariable("id")Integer id){
        Optional<MysqlBlog> byId = mysqlBlogRepository.findById(id);
        if (byId.isPresent()){
            MysqlBlog mysqlBlog = byId.get();
            return mysqlBlog;
        }
        return null;
    }

    @Data
    public static class Param{
        // mysql,es
        private String type;

        private String keyword;
    }

}
